package com.example.messengerserver;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class ServerService extends Service {
    private static final String TAG = "ServerService";
    /**
     * 服务端Messenger
     */
    Messenger serverMessenger;
    /**
     * 客户端 Messenger
     */
    Messenger clientMessenger = null;

    @Override
    public void onCreate() {
        super.onCreate();
        serverMessenger = new Messenger(handler);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return serverMessenger.getBinder();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                Log.d(TAG, "handleMessage:  收到客户端发来的消息");
                /**
                 * 保存客户端Messenger,用于向客户端发送消息
                 */
                if (msg.replyTo != null) {
                    clientMessenger = msg.replyTo;
                }
                Bundle bundle = msg.getData();
                String ms;
                if (bundle != null) {
                    ms = bundle.getString("serviceData");
                } else {
                    Log.d(TAG, "handleMessage: null bundle");
                    return;
                }
                if (ms == null) {
                    Toast.makeText(ServerService.this, "客户端收到空消息", Toast.LENGTH_LONG).show();
                    return;
                }
                /**
                 * 如果收到消息1 就往客户端发送一条消息
                 */
                if (ms.equals("1")) {
                    Message message = Message.obtain();
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("clientData", "2");
                    message.setData(bundle1);
                    try {
                        clientMessenger.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(ServerService.this, "收到客户端发来的消息" + ms, Toast.LENGTH_LONG).show();
                }
            }

        }
    };
}